package com.youlu.campus.admin.config;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.admin.auth.service.ResourceService;
import com.youlu.campus.common.exception.ApiErrorCode;
import com.youlu.campus.common.base.RestResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class UrlInterceptor extends HandlerInterceptorAdapter {
    @Value("${server.servlet.context-path:/campus-admin}")
    private String prefix;
    @Autowired
    ResourceService resourceService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
//        String uri = req.getRequestURI();
//        log.info(":>>> URL拦截-->检查URL1 isProtectedUrl:{}", uri);
//        if (StringUtils.isBlank(uri)) {
//            return true;
//        }
//        uri = uri.replace(prefix, "");
//        log.info(":>>> URL拦截-->检查URL2 isProtectedUrl:{}", uri);
//        String userId = AuthUtils.getUserId();
//        boolean hasPermission = resourceService.hasPermisson(userId, uri);
//        log.info(":>>> 用户:{},是否拥有URL:{},权限结果:{}", userId, uri, hasPermission);
//        if (!hasPermission) {
//            outJson(resp, AuthErrorCode.UNAUTHORIZED);
//        }
//        return hasPermission;
        return true;
    }

    public void outJson(ServletResponse response, ApiErrorCode errorCode) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding(CharEncoding.UTF_8);//设置编码
            response.setContentType("application/json; charset=utf-8");//设置返回类型
            out = response.getWriter();
            out.println(JSON.toJSONString(RestResultBuilder.builder().errorCode(errorCode).build()));//输出
        } catch (Exception e) {
            log.error("json out error:{}", e.getMessage());
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }

}
